<template>
  <div class="container">
    <div class="header">
      <h1>AI检测报告生成</h1>
      <p>输入任务批次ID，生成AI分析报告</p>
    </div>

    <div class="form-container">
      <div class="form-input">
        <el-input
            v-model.trim="taskBatchId"
            placeholder="请输入任务批次ID"
            clearable
            @keyup.enter="canGenerate && generateReport"
        >
          <template #prepend>批次ID</template>
        </el-input>
      </div>
      <el-button
          type="primary"
          :loading="loading"
          :disabled="!canGenerate || loading"
          @click="generateReport"
      >生成报告</el-button>
      <el-button
          v-if="reportContent"
          :disabled="loading"
          @click="saveReport"
      >保存报告</el-button>
    </div>

    <div v-if="loading" class="loading-text">
      <p>报告生成中，请稍候...</p>
      <el-progress :percentage="progressPercentage" :status="progressStatus" />
    </div>

    <div v-if="errorMessage" class="error-text">
      <el-alert :title="errorMessage" type="error" show-icon />
    </div>

    <div v-if="reportContent && !loading" class="result-container">
      <h3 class="report-title">AI生成报告</h3>
      <div class="report-content" v-html="formattedReport"></div>
    </div>

    <div v-if="!reportContent && !loading && !errorMessage" class="empty-container">
      <i class="el-icon-document"></i>
      <div>请先输入批次ID并生成报告</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const taskBatchId = ref('')
const loading = ref(false)
const reportContent = ref('')
const errorMessage = ref('')
const progressPercentage = ref(0)
const progressStatus = ref('')
const token = ref('')

onMounted(() => {
  token.value = localStorage.getItem('token') || 'mock-token-12345'
})

// 计算能否生成
const canGenerate = computed(() => !!taskBatchId.value && !loading.value)

const formattedReport = computed(() => {
  if (!reportContent.value) return ''
  // 转为 HTML 并简单转义
  return reportContent.value
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\n/g, '<br>')
})

// 生成报告
async function generateReport() {
  if (!canGenerate.value) return

  loading.value = true
  errorMessage.value = ''
  reportContent.value = ''
  progressPercentage.value = 0
  progressStatus.value = 'active'

  try {
    const response = await fetch(`/api/record/report?taskBatchId=${encodeURIComponent(taskBatchId.value)}`, {
      method: 'GET',
      headers: { 'Authorization': token.value }
    })

    if (!response.ok) throw new Error(`请求失败: ${response.status} ${response.statusText}`)

    const reader = response.body.getReader()
    const decoder = new TextDecoder('utf-8')
    let accumulatedContent = ''  // 添加累积内容变量
    let progress = 0

    while (true) {
      try {
        const { value, done } = await reader.read()
        if (done) {
          progressPercentage.value = 100
          progressStatus.value = 'success'
          loading.value = false
          ElMessage.success('报告生成成功！')
          break
        }

        // 累积新内容
        accumulatedContent += decoder.decode(value, { stream: true })

        await nextTick(() => {
          // 更新报告内容，使用累积的内容
          reportContent.value = accumulatedContent
        })

        // 模拟进度流畅增长
        progress = Math.min(progress + Math.max(2, Math.round(Math.random() * 7)), 96)
        progressPercentage.value = progress
      } catch (readError) {
        console.error('读取流错误:', readError)
        break
      }
    }
  } catch (error) {
    loading.value = false
    errorMessage.value = `生成报告失败: ${error.message}`
    progressStatus.value = 'exception'
    ElMessage.error(errorMessage.value)
    console.error('报告生成错误:', error)
  }
}

// 保存报告到本地
function saveReport() {
  try {
    const blob = new Blob([reportContent.value], {type: 'text/plain'})
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `检测报告_批次${taskBatchId.value}_${new Date().toISOString().slice(0, 10)}.txt`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)

    ElMessage.success('报告已保存到本地！')
  } catch (error) {
    ElMessage.error('保存报告失败！')
    console.error('保存错误:', error)
  }
}
</script>

<style scoped>
body {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  margin: 0;
  padding: 20px;
  min-height: 100vh;
  color: #333;
}

.container {
  max-width: 1000px;
  margin: 30px auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  overflow: hidden;
}

.header {
  background: linear-gradient(90deg, #409EFF 0%, #64b5ff 100%);
  color: white;
  padding: 25px 30px;
  text-align: center;
}

.header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
}

.header p {
  margin: 10px 0 0;
  opacity: 0.9;
}

.content {
  padding: 30px;
}

.form-container {
  display: flex;
  gap: 15px;
  margin-bottom: 30px;
  align-items: flex-end;
}

.form-input {
  flex: 1;
}

.result-container {
  border: 1px solid #e6e8eb;
  border-radius: 8px;
  padding: 20px;
  background-color: #f9fafc;
  min-height: 250px;
  max-height: 500px;
  overflow-y: auto;
  margin-top: 20px;
  transition: all 0.3s ease;
}

.result-container:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.report-title {
  color: #409EFF;
  margin-bottom: 15px;
  font-weight: bold;
  font-size: 18px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.button-group {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 25px;
}

.loading-container {
  text-align: center;
  padding: 20px;
}

.loading-text {
  color: #606266;
  margin-top: 15px;
  font-size: 15px;
}

.error-container, .empty-container {
  text-align: center;
  padding: 30px;
  color: #909399;
}

.empty-container i {
  font-size: 50px;
  opacity: 0.5;
  margin-bottom: 15px;
  display: block;
}

.stats {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  font-size: 13px;
  color: #909399;
}

.report-content {
  line-height: 1.6;
  white-space: pre-wrap;
}

.section {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px dashed #e6e8eb;
}

.section:last-child {
  border-bottom: none;
}

.section-title {
  font-weight: 600;
  color: #409EFF;
  margin-bottom: 8px;
}
</style>